package com.yuan.pay_mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuan.pay_mall.dao.ShippingMapper;
import com.yuan.pay_mall.enums.ResponseEnum;
import com.yuan.pay_mall.form.ShippingForm;
import com.yuan.pay_mall.pojo.Shipping;
import com.yuan.pay_mall.service.IShippingService;
import com.yuan.pay_mall.vo.ResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yuan.pay_mall.enums.ResponseEnum.DELETE_SHIPPING_FAIL;

@Service
public class ShippingServiceImpl implements IShippingService {
    @Autowired
    private ShippingMapper shippingMapper;
    @Override
    public ResponseVo<Map<String,Integer>> add(Integer uid, ShippingForm form) {
        Shipping shipping = new Shipping();
        //a对象的属性值拷贝到b对象的属性，是将两个字段相同的对象进行属性值的复制
        // https://blog.csdn.net/wjw_de_java/article/details/113742093
        BeanUtils.copyProperties(form,shipping);
        shipping.setUserId(uid);
        int row = shippingMapper.insertSelective(shipping);//写入成功就会返回影响的行数，成功就会是1，否0
        if(row ==0){
            return ResponseVo.error(ResponseEnum.ERROR);//服务器错误
        }
        Map<String,Integer> map = new HashMap<>();
        map.put("shippingId", shipping.getId());
        return ResponseVo.success(map);
    }

    @Override
    public ResponseVo delete(Integer uid, Integer shippingId) {
        int row = shippingMapper.deleteByIdAndUid(uid,shippingId);
        if(row==0){
            ResponseVo.error(DELETE_SHIPPING_FAIL);
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo upadate(Integer uid, Integer shippingId, ShippingForm form) {
        Shipping shipping =new Shipping();
        BeanUtils.copyProperties(form,shipping);
        shipping.setUserId(uid);
        shipping.setId(shippingId);
        int row = shippingMapper.updateByPrimaryKeySelective(shipping);
        if(row==0){
            return ResponseVo.error(ResponseEnum.ERROR);//服务器错误
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo<PageInfo> list(Integer uid, Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        List<Shipping> shippings = shippingMapper.selectByUid(uid);
        PageInfo pageInfo = new PageInfo(shippings);
        return ResponseVo.success(pageInfo);
    }
}


